//
//  HJDForgetViewController.m
//  JYHospital
//
//  Created by 胡金东 on 16/6/1.
//  Copyright © 2016年 胡金东. All rights reserved.
//

#import "HJDForgetViewController.h"
#import "AFNetworking.h"
#import <CommonCrypto/CommonDigest.h>


#define HJDHorVM 46
@interface HJDForgetViewController (){
    BOOL type;
}


@property (nonatomic,assign) int  second;
@property (nonatomic,strong) UIButton *btn;
@property (nonatomic,strong) NSTimer * timer;

@property (nonatomic,strong) UITextField  *phoneField;
@property (nonatomic,strong) UITextField *mesTestText;
@property (nonatomic,strong) UITextField  *passwordtextField;
@property (nonatomic,strong) UITextField  *passwordSecondtextField;



@end

@implementation HJDForgetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"忘记密码";
    [self.navigationController.navigationBar setTitleTextAttributes:
     @{NSFontAttributeName:[UIFont systemFontOfSize:19],
       NSForegroundColorAttributeName:[UIColor getColorWithHexNumber:@"848484"]}];

    self.view.backgroundColor = [UIColor whiteColor];
    [self setUpTextFiled];
    self.second = 60;
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(popToPre) image:@"︿" HighImage:nil];
    //添加手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped:)];
    tap.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tap];
   
}

//隐藏键盘
-(void)viewTapped:(UITapGestureRecognizer*)tap
{
    
    [self.view endEditing:YES];
    
}

//返回
-(void)popToPre
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
-(void)setUpTextFiled{
    CGFloat phoneX = HJDHorVM;
    CGFloat phoneY = 81;
    CGFloat phoneW = HJDWidth - 46*2;
    CGFloat phoneH = 40;
    self.phoneField = [[UITextField alloc]initWithFrame:CGRectMake(phoneX, phoneY, phoneW, phoneH)];
    self.phoneField.keyboardType = UIKeyboardTypeNumberPad;
    self.phoneField.clearButtonMode = UITextFieldViewModeAlways;
    self.phoneField.placeholder = @"输入手机号";
    [self.phoneField setValue:[UIFont systemFontOfSize:18] forKeyPath:@"_placeholderLabel.font"];
    [self.phoneField setValue:[UIColor getColorWithHexNumber:@"B3B3B3"] forKeyPath:@"_placeholderLabel.textColor"];
    
    [self.view addSubview:self.phoneField];
    
    //    横线
    CGFloat viewX = HJDHorVM ;
    CGFloat viewY = CGRectGetMaxY(self.phoneField.frame);
    CGFloat viewW = phoneW;
    CGFloat viewH = 1;
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(viewX, viewY, viewW, viewH)];
    view.backgroundColor = [UIColor getColorWithHexNumber:@"B3B3B3"];
    [self.view addSubview:view];
    
    CGFloat mesTestTextX = HJDHorVM;
    CGFloat mesTestTextY = CGRectGetMaxY(view.frame) + HJDVerticalMargin;
    CGFloat mesTestTextW = phoneW - 120;
    CGFloat mesTestTextH = phoneH;
    self.mesTestText = [[UITextField alloc]initWithFrame:CGRectMake(mesTestTextX, mesTestTextY, mesTestTextW, mesTestTextH)];
    self.mesTestText.clearButtonMode = UITextFieldViewModeAlways;
    self.mesTestText.keyboardType = UIKeyboardTypeNumberPad;
    self.mesTestText.placeholder = @"输入验证码";
    [self.mesTestText setValue:[UIFont systemFontOfSize:18] forKeyPath:@"_placeholderLabel.font"];
    [self.mesTestText setValue:[UIColor getColorWithHexNumber:@"B3B3B3"] forKeyPath:@"_placeholderLabel.textColor"];
    self.mesTestText.keyboardType = UIKeyboardTypeNumberPad;
    [self.view addSubview:self.mesTestText];
    
    CGFloat btnX = CGRectGetMaxX(self.mesTestText.frame);
    CGFloat btnY = mesTestTextY;
    CGFloat btnW = 120;
    CGFloat btnH = mesTestTextH;
    
    self.btn = [[UIButton alloc]initWithFrame:CGRectMake(btnX, btnY, btnW, btnH)];
    [self.btn setTitle:@"获取验证码" forState:UIControlStateNormal];
    self.btn.titleLabel.font = [UIFont systemFontOfSize:15];
    [self.btn setRadius:10 borderWith:0 borderColor:nil];
    [self.btn setBackgroundColor:[UIColor getColorWithHexNumber:@"FF9EAC"]];
    [self.btn addTarget:self action:@selector(mesTestBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.btn];
    //    横线
    CGFloat mesTestviewX = HJDHorVM ;
    CGFloat mesTestviewY = CGRectGetMaxY(self.mesTestText.frame);
    CGFloat mesTestviewW = mesTestTextW ;
    CGFloat mesTestviewH = 1;
    UIView *mesTestview = [[UIView alloc]initWithFrame:CGRectMake(mesTestviewX, mesTestviewY, mesTestviewW, mesTestviewH)];
    mesTestview.backgroundColor = [UIColor getColorWithHexNumber:@"B3B3B3"];
    [self.view addSubview:mesTestview];
    
    
    CGFloat passwordX = HJDHorVM ;
    CGFloat passwordY = CGRectGetMaxY(self.btn.frame) + HJDVerticalMargin;
    CGFloat passwordW = phoneW;
    CGFloat passwordH = phoneH;
   self.passwordtextField = [[UITextField alloc]initWithFrame:CGRectMake(passwordX, passwordY,passwordW, passwordH)];
    self.passwordtextField.secureTextEntry = YES;
    self.passwordtextField.clearButtonMode = UITextFieldViewModeAlways;

    self.passwordtextField.placeholder = @"重置密码：";
    [self.passwordtextField setValue:[UIFont systemFontOfSize:18] forKeyPath:@"_placeholderLabel.font"];
    [self.passwordtextField setValue:[UIColor getColorWithHexNumber:@"B3B3B3"] forKeyPath:@"_placeholderLabel.textColor"];
    [self.passwordtextField addTarget:self action:@selector(textPassChange) forControlEvents:UIControlEventEditingChanged];
    
    [self.view addSubview:self.passwordtextField];
    //    横线
    CGFloat passwordviewX = HJDHorVM;
    CGFloat passwordviewY = CGRectGetMaxY(self.passwordtextField.frame);
    CGFloat passwordviewW = phoneW;
    CGFloat passwordviewH = 1;
    UIView *passwordview = [[UIView alloc]initWithFrame:CGRectMake(passwordviewX, passwordviewY, passwordviewW, passwordviewH)];
    passwordview.backgroundColor = [UIColor getColorWithHexNumber:@"B3B3B3"];
    [self.view addSubview:passwordview];
    
    
    
    CGFloat passwordSecondX = HJDHorVM;
    CGFloat passwordSecondY = CGRectGetMaxY(passwordview.frame) + HJDVerticalMargin;
    CGFloat passwordSecondW = phoneW;
    CGFloat passwordSecondH = phoneH;
   self.passwordSecondtextField = [[UITextField alloc]initWithFrame:CGRectMake(passwordSecondX, passwordSecondY,passwordSecondW, passwordSecondH)];
    self.passwordSecondtextField.clearButtonMode = UITextFieldViewModeAlways;
    self.passwordSecondtextField.secureTextEntry = YES;
    self.passwordSecondtextField.placeholder = @"确认密码：";
    [self.passwordSecondtextField setValue:[UIFont systemFontOfSize:18] forKeyPath:@"_placeholderLabel.font"];
    
    [self.passwordSecondtextField setValue:[UIColor getColorWithHexNumber:@"B3B3B3"] forKeyPath:@"_placeholderLabel.textColor"];
    [self.passwordtextField addTarget:self action:@selector(textPassSChange) forControlEvents:UIControlEventEditingChanged];

    
    [self.view addSubview:self.passwordSecondtextField];
    //    横线
    CGFloat passwordSecondviewX = HJDHorVM ;
    CGFloat passwordSecondviewY = CGRectGetMaxY(self.passwordSecondtextField.frame);
    CGFloat passwordSecondviewW = phoneW;
    CGFloat passwordSecondviewH = 1;
    UIView *passwordSecondview = [[UIView alloc]initWithFrame:CGRectMake(passwordSecondviewX, passwordSecondviewY, passwordSecondviewW, passwordSecondviewH)];
    passwordSecondview.backgroundColor = [UIColor getColorWithHexNumber:@"B3B3B3"];
    [self.view addSubview:passwordSecondview];
    
    
    
    CGFloat loginbtnX = HJDHorVM;
    CGFloat loginbtnY = CGRectGetMaxY(passwordSecondview.frame) + 38;
    CGFloat loginbtnW = phoneW;
    CGFloat loginbtnH = 50;
    UIButton *loginbtn = [[UIButton alloc]initWithFrame:CGRectMake(loginbtnX, loginbtnY, loginbtnW, loginbtnH)];
    [loginbtn setTitle:@"提交" forState:UIControlStateNormal];
    loginbtn.titleLabel.font = [UIFont systemFontOfSize:19];
    [loginbtn setRadius:10 borderWith:0 borderColor:nil];
    [loginbtn setBackgroundColor:[UIColor getColorWithHexNumber:@"5CC6AC"]];
    [loginbtn addTarget:self action:@selector(loginbtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:loginbtn];
    
    
}


-(void)textPassChange
{
    
    NSRange _range = [self.passwordtextField.text rangeOfString:@" "];
    if (_range.location != NSNotFound) {
                [MBProgressHUD showError:@"不可输入空格，请重新输入"];

    }
   
}
-(void)textPassSChange
{
    
    NSRange _range = [self.passwordSecondtextField.text rangeOfString:@" "];
    if (_range.location != NSNotFound) {
        [MBProgressHUD showError:@"不可输入空格，请重新输入"];
        
    }
    
}


-(NSString *)md5:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, strlen(cStr), result);
    NSMutableString *hash = [NSMutableString string];
    for (int i = 0; i < 16; i++)
    {
        [hash appendFormat:@"%02X", result[i]];
    }
    return [hash lowercaseString];
}



-(void)mesTestBtnClick
{
    NSString *phone = @"^1+[34578]+\\d{9}";
    NSPredicate *pr = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phone];
        
    if ([pr evaluateWithObject:self.phoneField.text ]) {
  
        
        NSString *url = @"/app/smsSend.do";
        NSString *path = [Hurl stringByAppendingString:url];
        
        AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        params[@"phone"] = self.phoneField.text;
         params[@"type"] = @"false";
        [mgr POST:path parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *infoDic = (NSDictionary*)responseObject;
            NSString *successfolStr = infoDic[@"resultCode"];
            NSLog(@"%@",successfolStr);
            
           
                [self sendVerificationCode];
            
            HJDLog(@"%@",responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [MBProgressHUD showError:@"发送失败"];
            HJDLog(@"%@",error);
        }];
        
    }else{
        [MBProgressHUD showError:@"请输入正确的手机号"];
    }
    

}

-(void)loginbtnClick
{
    
    
    
    if (self.mesTestText.text.length >0 ) {
        if (self.mesTestText.text.length == 6) {
            NSRange _range = [self.passwordtextField.text rangeOfString:@" "];
            if (_range.location == NSNotFound) {
                NSRange _range = [self.passwordSecondtextField.text rangeOfString:@" "];
                if (_range.location == NSNotFound) {

            
        NSString *url = @"/app/modifyPD.do";
        NSString *path = [Hurl stringByAppendingString:url];
        AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
            
            NSString *strr = [self md5:self.passwordtextField.text];
            NSLog(@"%@",strr);

        params[@"phone"] = self.phoneField.text;
        params[@"code"] = self.mesTestText.text;

        params[@"password"] = strr;
        
        [mgr POST:path parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *dict = (NSDictionary *)responseObject;
            NSString *resultCode = dict[@"resultCode"];
            
            
            if ([self.passwordtextField.text isEqualToString:self.passwordSecondtextField.text]) {
                
                if ([resultCode integerValue]==005) {
                    [MBProgressHUD showSuccess:@"验证码失效或错误"];
                }else{
                
                [MBProgressHUD showSuccess:@"修改密码成功"];
                    [self dismissViewControllerAnimated:YES completion:nil];

                HJDLog(@"%@",responseObject);
                }
            }else{
                [MBProgressHUD showError:@"两次密码不一致"];
            }
            
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [MBProgressHUD showError:@"修改密码失败"];
            HJDLog(@"%@",error);
        }];
                }else{
                    [MBProgressHUD showError:@"确认密码有空格，请重新输入"];
                }
                    }else{
                        [MBProgressHUD showError:@"重置密码有空格，请重新输入"];
                    }
        }else{
            [MBProgressHUD showError:@"验证码长度不对"];
        }
    }else{
        [MBProgressHUD showError:@"验证码不能为空"];
    }
    
}
-(void)changeMin
{
    if (self.second == 0) {
        
        [self.btn setTitle:@"重新获取验证码" forState:UIControlStateNormal];
        self.btn.enabled = YES;
        self.btn.hidden = NO;
        [self.timer invalidate];
        self.second = 60;
        return;
    }
    
    self.btn.enabled = NO;
    [self.btn setTitle:[NSString stringWithFormat:@"%d s",self.second] forState:UIControlStateNormal];
    self.second --;
    
}
- (void)sendVerificationCode
{
             self.timer = [NSTimer scheduledTimerWithTimeInterval:1
                                                          target:self selector:@selector(changeMin)
                                                        userInfo:nil repeats:YES];
   }





@end
